exports.__esModule = true;

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

// const uuid = require('node-uuid');

exports.default = class extends think.Service {
    constructor() {
        super();
        this.userModel = this.db['sys_user'];
        this.orgModel = this.db['sys_org'];
        this.orgModel.hasMany(this.userModel, { foreignKey: 'org_id' });
        this.defData = {
            userid: '000000',
            roleid: '000000'
        };
    }
    /**
     * 查询部门名称列表unBindUser
     */
    getDepartName(userInfo) {
        var _this = this;

        return _asyncToGenerator(function* () {
            const aj = {
                success: false,
                msg: '',
                result: {}
            };
            try {
                // const data = await this   .orgModel   .findAll({     attributes: ['id',
                // 'org_name', 'org_code', 'parent_id', 'parent_ids']   });
                const options = {
                    attributes: ['id', 'org_name', 'org_code', 'parent_id', 'parent_ids']
                };
                const data = yield _this.BaseService.dataScopeFilter('sys_org', userInfo, options);
                aj.result = data;
                aj.success = true;
                return aj;
            } catch (err) {
                return _this.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 查询部门名称列表unBindUser
     */
    getDepartNameAll(userInfo) {
        var _this2 = this;

        return _asyncToGenerator(function* () {
            const aj = {
                success: false,
                msg: '',
                result: {}
            };
            try {
                const data = yield _this2.orgModel.findAll({
                    attributes: ['id', 'org_name', 'org_code', 'parent_id', 'parent_ids']
                });
                // const options = {     attributes: ['id', 'org_name', 'org_code', 'parent_id',
                // 'parent_ids'] }; const data = await this     .BaseService
                // .dataScopeFilter('sys_org', userInfo, options);
                aj.result = data;
                aj.success = true;
                return aj;
            } catch (err) {
                return _this2.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 保存部门信息
     * @data
     *
     */
    saveDepartInfo(data) {
        var _this3 = this;

        return _asyncToGenerator(function* () {
            const aj = {
                success: false,
                msg: '',
                result: {}
            };
            aj.success = false;
            try {
                const depart = yield _this3.orgModel.findOne({
                    where: {
                        org_code: data.org_code
                    },
                    attributes: ['id']
                });
                // if (!data.id) {     data.id = think.uuid('v1'); }
                if (depart) {
                    if (depart.id !== data.id) {
                        aj.msg = '组织机构编码已存在，请重新输入';
                        return aj;
                    }
                }
                // if (!data.id) {
                yield new _this3.TreeService().saveTree('sys_org', data.parent, data);
                // } else {     await this.orgModel.upsert(data); }
                aj.success = true;
                return aj;
            } catch (err) {
                return _this3.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 查询部门信息
     */
    getDepartList(data, userInfo) {
        var _this4 = this;

        return _asyncToGenerator(function* () {
            const aj = {
                success: false,
                msg: '',
                result: {}
            };
            const where = {};
            if (data.org_type) {
                where.org_type = data.org_type;
            }
            try {
                // const list = await this   .orgModel   .findAll({     where: where   }); const
                const list = yield _this4.BaseService.dataScopeFilter('sys_org', userInfo);
                let Res = {};
                if (data.org_type) {
                    Res = list.filter(function (item) {
                        return item.org_type == data.org_type;
                    });
                } else {
                    Res = list;
                }
                aj.success = true;
                aj.result = Res;
                return aj;
            } catch (err) {
                return _this4.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 删除部门信息/单条删除
     */
    delDepartInfo(data) {
        var _this5 = this;

        return _asyncToGenerator(function* () {
            const aj = {
                success: false,
                msg: '',
                result: {}
            };
            const where1 = {
                org_id: data.id,
                del_flag: 0
            };
            const where2 = {
                id: data.id
            };
            try {
                const userCount = yield _this5.userModel.count({ where: where1 });
                if (userCount > 0) {
                    aj.msg = '所选部门下有用户，请先删除对应用户信息';
                } else {
                    const delDepart = yield _this5.orgModel.destroy({ where: where2 });
                    if (delDepart) {
                        aj.success = true;
                    }
                }
                return aj;
            } catch (err) {
                return _this5.exceptionService.handleError(err);
            }
        })();
    }
    /** ***************与用户相关****************** */
    /** ***************与用户相关****************** */
    /**
     * 部门用户解绑
     */
    unBindUser(data) {
        var _this6 = this;

        return _asyncToGenerator(function* () {
            const aj = {
                success: false,
                msg: '',
                result: {}
            };
            const upData = {
                org_id: null
            };
            const where = {
                where: {
                    id: data.userid
                }
            };
            try {
                const userRes = yield _this6.userModel.update(upData, where);
                if (userRes) {
                    aj.success = true;
                } else {
                    aj.msg = '解绑错误';
                }
                return aj;
            } catch (err) {
                return _this6.exceptionService.handleError(err);
            }
        })();
    }

    /**
     * 获取未分配部门的用户
     */
    getUserNotBindOrg(data) {
        var _this7 = this;

        return _asyncToGenerator(function* () {
            data.start = (parseInt(data.page) - 1) * parseInt(data.pageSize);
            const aj = {
                success: false,
                msg: '',
                result: {}
            };
            try {
                const where = {
                    id: {
                        [_this7.db.Sequelize.Op.not]: _this7.defData.userid // 排除系统预设用户
                    },
                    [_this7.db.Sequelize.Op.or]: [{
                        org_id: ''
                    }, {
                        org_id: null
                    }]
                };
                var optJson = JSON.parse(data.options);
                if (!think.isEmpty(optJson)) {
                    where.username = {
                        [_this7.db.Sequelize.Op.like]: '%' + optJson.username + '%'
                    };
                }
                const userListRes = yield _this7.userModel.findAndCountAll({
                    where: where,
                    limit: parseInt(data.pageSize),
                    offset: parseInt(data.start)
                });
                aj.result = userListRes;
                aj.success = true;
                return aj;
            } catch (err) {
                return _this7.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 批量绑定用户到部门
     * @data
     * data.userlist --用户id数组
     * data.org_id --部门id
     */

    saveUsersDepart(data) {
        var _this8 = this;

        return _asyncToGenerator(function* () {
            const aj = {
                success: false,
                msg: '',
                result: {}
            };
            const upData = {
                org_id: data.org_id
            };
            const where = {
                where: {
                    id: {
                        [_this8.db.Sequelize.Op.in]: data.userlist
                    }
                }
            };
            try {
                const userRes = yield _this8.userModel.update(upData, where);
                if (userRes) {
                    aj.msg = '保存成功';
                    aj.success = true;
                } else {
                    aj.msg = '绑定部门错误';
                }
                return aj;
            } catch (err) {
                return _this8.exceptionService.handleError(err);
            }
        })();
    }

    /**
     * 获取部门及其用户数据
     * @param {Object} data
     */
    getOrgAndUser(userInfo) {
        var _this9 = this;

        return _asyncToGenerator(function* () {
            try {
                let where = {};
                const newWhere = yield _this9.BaseService.getDataScopeWhere(userInfo, 1);
                if (newWhere instanceof Object) {
                    where = newWhere;
                    console.log('where:', where);
                } else {
                    if (Number(newWhere) == 4) {
                        const { userId } = userInfo;
                        where.create_by = userId;
                    }
                }
                // if (data.org_name) {     where.org_name = {         $like: '%' +
                // data.org_name + '%'     } }
                const org = yield _this9.orgModel.findAll({
                    where: where,
                    include: [{
                        model: _this9.userModel,
                        where: {
                            del_flag: 0
                        },
                        attributes: ['id', 'realname', 'org_id', 'phone'],
                        required: false
                    }],
                    order: [['org_code', 'ASC']]
                });
                // let list = [] if (org) {     if (data.id) { console.log('org存在-----------')
                // console.log(data.id);         // list = this.getChild(org, data.id) list =
                // org     } else {         list = org     } }
                return org;
            } catch (error) {
                return _this9.exceptionService.handleError(error);
            }
        })();
    }
};